package com.nwpu.coursesupport.service.imple;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nwpu.coursesupport.criteria.ResourceSearchCriteria;
import com.nwpu.coursesupport.entity.Resource;
import com.nwpu.coursesupport.entity.Student;
import com.nwpu.coursesupport.entity.bean.Files.FileItem;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.FileType;
import com.nwpu.coursesupport.enumeration.RoleType;
import com.nwpu.coursesupport.mapper.ResourceMapper;
import com.nwpu.coursesupport.mapper.StudentMapper;
import com.nwpu.coursesupport.pagination.PageBounds;
import com.nwpu.coursesupport.service.AbstractService;
import com.nwpu.coursesupport.service.param.IDListParam;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.ResourceServiceParam;
import com.nwpu.coursesupport.service.param.ResourceServiceParam.DeleteParam;
import com.nwpu.coursesupport.tool.UpdateUtil;


@Service
public class ResourceService extends AbstractService{
    @Autowired
    private ResourceMapper resourceMapper;
    
    @Autowired
    private StudentMapper studentMapper;

    protected static Logger logger = LoggerFactory.getLogger(ResourceService.class);

    
    public Resource detail(String key){        
        if(key==null||key.equals("")){
        	logger.error("key为空");
        	return null;
        }
        Resource resource = this.resourceMapper.findByKey(key);
      
        return resource;
    }
    
    public Student getStudent(int id){
    	if(id < 0){
    		logger.error("id错误");
    		return null;
    	}
    	Student student = this.studentMapper.findById(id);
    	return student;
    }
    
    //学生上传的文件名中不包含学号，则加上
    public String formatName(String s){
		int id = (int) getSession().getAttribute("id");
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		if(roleType == RoleType.STUDENT){
			Student student = this.studentMapper.findById(id);
			String studentCode = student.getStudentCode();
			if(s.indexOf(studentCode) != -1){
				return s;
			}else{
				return studentCode+"_"+s;
			}
		}else {
			return s;
		}
    }

    public List<Resource> list(ResourceSearchCriteria  sc){
       
        if (sc == null){
        	logger.error("查询参数为空");
            return null;
        }
        List<Resource> list = this.resourceMapper.find(sc);
        return list;
    }

    public JSONResult listData(ResourceServiceParam.SearchParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
       
        if (p == null){
        	logger.error("参数为空");
            return rst.fail("参数有误");
        }

        ResourceSearchCriteria sc = p.getSearch();
        if (sc == null){
            sc = new ResourceSearchCriteria();
        }
        
        PageBounds page = new PageBounds();
        page.setNumber(1);
        page.setSize(10);
        
        List<Resource> list = this.resourceMapper.find(sc, page);
        if (list == null){
        	logger.error("数据查询失败");
            return rst.fail("数据查询失败");
        }
        
        rst.addData("list", list);
        rst.addData("search", sc);
        rst.addData("pageBounds", page);
        rst.success();
        return rst;
    }

    public JSONResult create(Resource resource){
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (resource == null){
        	logger.error("参数有误");
            return rst.fail("参数有误");
        }

        if (!this.resourceMapper.save(resource)){
        	logger.error("保存失败");
            return rst.fail("保存失败");
        }
        
        rst.addData("resource", resource);
        rst.success();
        return rst;
    }

    public JSONResult update(ResourceServiceParam.UpdateParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null || p.getId() <= 0){
        	logger.error("参数有误");
            return rst.fail("参数有误");
        }
        
        Resource resource = this.resourceMapper.findById(p.getId());
        if (resource == null){
        	logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }
        
        if (UpdateUtil.setValues(resource, p) > 0){
        	 if (!this.resourceMapper.update(resource)){
        		 logger.error("保存失败");
                 return rst.fail("保存失败");
             }
        }
       
        rst.addData("resource", resource);
        rst.success();
        return rst;
    }
    
    public JSONResult delete(DeleteParam p) throws Exception{
    	JSONResult rst = new JSONResult();
    	rst.fail();
    	
    	if(p == null){
    		logger.error("参数有误");
    		rst.fail("参数有误");
    		return rst;
    	}
    	
		int id = (int) getSession().getAttribute("id");
		List<Resource> listR = this.resourceMapper.findByKeys(p.getKeys());
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0;i<listR.size();i++){
			if(listR.get(i).getUploadId() == id && listR.get(i).getFileType()!=FileType.FEMAIL&& listR.get(i).getFileType()!=FileType.MALE&& listR.get(i).getFileType()!=FileType.UNLOAD){
				list.add(new Integer(listR.get(i).getId()));
			}
		}
		if(list.size() > 0){
			if(!this.resourceMapper.batchDelete(list)){
				logger.error("删除失败");
				rst.fail("删除失败");
				return rst;
			}
		}
		
		rst.success();		
    	return rst;
    }
    public JSONResult remove(IDParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null || p.getId() <= 0){
        	logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }
        
        Resource resource = this.resourceMapper.findById(p.getId());
        if (resource == null){
        	logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }

        if (!this.resourceMapper.delete(p.getId())){
        	logger.error("删除失败");
            return rst.fail("删除失败");
        }
        rst.addData("resource", resource);
        rst.success();
        return rst;
    }

    public JSONResult removeAll(IDListParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null || p.getIds() == null || p.getIds().isEmpty()){
        	logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }
        
        this.resourceMapper.batchDelete(p.getIds());

        rst.success();
        return rst;
    }

	public List<Resource> getNameUrl(List<FileItem> filist) {
		// TODO 
		List<Resource> rl = new ArrayList<>();
		Resource r = new Resource();
		for(FileItem fi : filist){
			r = this.resourceMapper.findByKey(fi.getUrl());
			if(r != null){
				r.setFileName(fi.getName());
				rl.add(r);
			}
		}
		return rl;
	}



}
